package com.hm.PushCaseService.service.push.log;

import com.hm.PushCaseService.mapper.push.log.PushLogMapper;
import com.hm.PushCaseService.pojo.PushLogParams;
import com.hm.PushCaseService.pojo.response.PushLogBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class PushService implements IPush {
    private static final Logger logger = LoggerFactory.getLogger(PushService.class);

    @Qualifier("MainSqlSessionFactory")
    private final SqlSessionFactory sqlSessionFactory;

    public PushService(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public List<PushLogBean> queryPushLog(int pageSize, int pageIndex) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            PushLogMapper mapper = session.getMapper(PushLogMapper.class);
            PushLogParams params = new PushLogParams();
            params.pageSize = pageSize;
            if (pageIndex == 1) {
                pageIndex = 0;
            } else {
                pageIndex = pageIndex * pageSize;
            }
            params.pageIndex = pageIndex;
            return mapper.queryPushLog(params);
        }
    }

    @Override
    public void addPushLog(PushLogBean bean) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            PushLogMapper mapper = session.getMapper(PushLogMapper.class);
            Map<String, String> params = new HashMap<>();
            params.put("eventCode", bean.eventCode);
            params.put("responseState", bean.responseState);
            params.put("pushState", bean.pushState);
            params.put("pushTime", bean.pushTime);
            mapper.addPushLog(params);
        }
    }

    @Override
    public Integer queryCount() {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            PushLogMapper mapper = session.getMapper(PushLogMapper.class);
            return mapper.queryCount();
        }
    }
}
